<template>
  <view class="container">
    <!-- 头部 -->
    <view class="head"
      style="background-color: #ffcc00;
      height: 180rpx;
      display: flex;">
      <img
        style="height: 50rpx;
        width: 50rpx;
        padding: 10rpx;
        margin-top: 15%;"  
        src="../../../static/tabbar/返回.png" 
        alt="" 
        @click="handleBack"
      />
      <view style="
        height: fit-content;
        margin-top: 15%;
        margin-left: 30%;
        font-size: 32rpx;"
      >等待付款</view>
    </view>

    <!-- 购买须知 -->
    <view class="purchase-notice">
      <text class="title">购买须知：
        
      </text>
      <text class="content">{{ purchaseNotice }}</text>
    </view>

    <!-- 用户信息 -->
    <view class="info-section" @click="showEditModal">
      <view class="info-item">
        <text class="label">姓名：</text>
        <text class="value">{{ userInfo.name }}</text>
      </view>
      <view class="info-item">
        <text class="label">电话：</text>
        <text class="value">{{ userInfo.phone }}</text>
      </view>
      <view class="info-item">
        <text class="label">地址：</text>
        <text class="value">{{ userInfo.address }}</text>
      </view>
      <view class="info-item">
        <text class="label">自理情况：</text>
        <text class="value">{{ userInfo.selfCare }}</text>
      </view>
    </view>

    <!-- 新增预约日期栏 -->
    <view class="date-section">
      <view class="uni-list-cell">
        <view class="tit">预约日期</view>
        <view class="uni-list-cell-db">
          <picker 
            mode="date" 
            :value="selectedDate" 
            :start="startDate" 
            :end="endDate" 
            fields="day" 
            @change="bindDateChange"
          >
            <view class="uni-input">{{ selectedDate || '请选择预约日期' }}</view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <view class="edit-modal">
        <view class="edit-item">
          <text class="label">姓名：</text>
          <uni-easyinput v-model="editForm.name" placeholder="请输入姓名" />
        </view>
        <view class="edit-item">
          <text class="label">电话：</text>
          <uni-easyinput v-model="editForm.phone" placeholder="请输入电话" />
        </view>
        <view class="edit-item">
          <text class="label">地址：</text>
          <uni-easyinput v-model="editForm.address" placeholder="请输入地址" />
        </view>
        <view class="edit-item">
          <text class="label">自理情况：</text>
          <uni-easyinput v-model="editForm.selfCare" placeholder="请输入自理情况" />
        </view>
        <view class="action-buttons">
          <button class="cancel-btn" @click="handleEditClose">取消</button>
          <button class="confirm-btn" @click="handleEditConfirm">保存</button>
        </view>
      </view>
    </uni-popup>


    <!-- 服务信息 -->
    <view class="service-section">
      <text class="title">服务详情</text>
      <view v-for="(service, index) in services" :key="index" class="service-item">
        <text class="name">{{ service.serviceName }}</text>
        <text class="price">{{ service.priceDescription }}</text>
      </view>
    </view>

    <!-- 总金额
    <view class="total-amount">
      <text class="label">总金额：</text>
      <text class="value">¥ {{ totalAmount }}</text>
    </view> -->

    

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="cancel-btn" @click="handleCancel">取消订单</button>
      <button class="confirm-btn" @click="handleConfirm">联系客服购买</button>
    </view>
  </view>
</template>

<script setup>

import { ref, onMounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { updateUserInfo, userBuyService, getWxUserInfo } from '@/api/wxlogin/wxlogin';





const services = ref([]);
const totalAmount = ref(0);
const purchaseNotice = ref('');

// 通过getWxUserInfo获取用户信息
const userInfo = ref({
  // name: '张三',
  // phone: '13800138000',
  // address: '北京市朝阳区XX街道XX号',
  // selfCare: '完全自理'
});

// 编辑相关状态
const editPopup = ref(null);
const editForm = ref({...userInfo.value});

const showEditModal = () => {
  editForm.value = {...userInfo.value};
  editPopup.value.open();
};

const handleEditConfirm = async () => {
  try {
    const userId = uni.getStorageSync('userId');
    console.log(userId);
    const updateData = {
      userId: userId,
      name: editForm.value.name,
      phone: editForm.value.phone,
      address: editForm.value.address,
      selfCareStatus: editForm.value.selfCare
    };

    const res = await updateUserInfo(updateData);
    
    if (res.code === 200) {
      // 更新本地用户信息
      userInfo.value = {...editForm.value};
      editPopup.value.close();
      uni.showToast({
        title: '信息更新成功',
        icon: 'success'
      });
    } else {
      throw new Error(res.message || '更新失败');
    }
  } catch (err) {
    console.error('更新用户信息失败:', err);
    uni.showToast({
      title: '信息更新失败，请重试',
      icon: 'none'
    });
  }
};

const handleEditClose = () => {
  editPopup.value.close();
};

const handleBack = () => {
  uni.navigateBack();
};

const handleCancel = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack();
      }
    }
  });
};

const selectedDate = ref('');

const startDate = computed(() => {
  return getDate('start');
});

const endDate = computed(() => {
  return getDate('end');
});

const bindDateChange = (e) => {
  selectedDate.value = e.detail.value;
  console.log('Selected date:', selectedDate.value);
};

const getDate = (type) => {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  if (type === 'start') {
    year = year - 60; // Allow selection of dates up to 60 years ago
  } else if (type === 'end') {
    year = year + 2; // Allow selection of dates up to 2 years in the future
  }
  
  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;
  
  return `${year}-${month}-${day}`;
};

const handleConfirm = async () => {
  // 检查服务数据是否存在
  if (!services.value.length || !services.value[0]) {
    uni.showToast({
      title: '服务信息获取失败，请重试',
      icon: 'none'
    });
    return;
  }

  // 检查必填字段
  const requiredFields = {
    name: '姓名',
    phone: '电话',
    address: '地址',
    selfCare: '自理情况'
  };
  
  const missingFields = Object.entries(requiredFields)
    .filter(([field]) => !userInfo.value[field])
    .map(([_, label]) => label);

  if (missingFields.length > 0) {
    uni.showToast({
      title: `请先完善以下信息：${missingFields.join('，')}`,
      icon: 'none',
      duration: 3000
    });
    return;
  }

  if (!selectedDate.value) {
    uni.showToast({
      title: '请选择预约日期',
      icon: 'none',
      duration: 3000
    });
    return;
  }

  try {
    const purchaseData = {
      userId: uni.getStorageSync('userId'),
      serviceName: services.value[0].serviceName,
      appointmentDate: selectedDate.value
    };

    const res = await userBuyService(purchaseData);
    
    if (res.code === 200) {
      uni.showToast({
        title: '购买请求已发送',
        icon: 'success'
      });
      
      uni.navigateTo({
        url: '/pages/customer-platform/my/customerService'
      });
    } else {
      throw new Error(res.message || '购买请求发送失败');
    }
  } catch (err) {
    console.error('购买服务失败:', err);
    uni.showToast({
      title: err.message || '购买服务失败，请重试',
      icon: 'none'
    });
  }
};

onLoad((options) => {
  // 处理从homeClean或serviceBooking页面传递的服务数据
  if (options.service) {
    const service = JSON.parse(decodeURIComponent(options.service));
    services.value = [service];
    totalAmount.value = service.price || 0;
    purchaseNotice.value = service.notice || '';
  }

  // 获取用户信息
  if (uni.getStorageSync('isLoggedIn')) {
    const userId = uni.getStorageSync('userId');
    console.log("userId:", userId);
    getWxUserInfo(userId).then(res => {
      if (res.code === 200) {
        const { name, phone, address, selfCareStatus } = res.data;
        userInfo.value = {
          name: name || '',
          phone: phone || '',
          address: address || '',
          selfCare: selfCareStatus || ''
        };
      }
    }).catch(err => {
      console.error('获取用户信息失败:', err);
    });
  }
});
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #fff;
  min-height: 100vh;
}

.info-section {
  padding: 24rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  margin: 24rpx;
  cursor: pointer;
  transition: background-color 0.3s;

  &:active {
    background-color: #f0f0f0;
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .label {
      font-size: 28rpx;
      color: #666;
      width: 120rpx;
    }

    .value {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.service-section {
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin: 24rpx;

  .title {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 24rpx;
  }

  .service-item {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    margin-bottom: 16rpx;

    .name {
      font-size: 28rpx;
      color: #333;
    }

    .price {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.total-amount {
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .label {
    font-size: 32rpx;
    color: #333;
  }

  .value {
    font-size: 32rpx;
    color: #ff0000;
    font-weight: bold;
  }
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 24rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);

  button {
    flex: 1;
    margin: 0 12rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
  }

  .cancel-btn {
    background-color: #f5f5f5;
    color: #333;
  }

  .confirm-btn {
    background-color: #ffcc00;
    color: #333;
  }
}

.edit-modal {
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  width: 80vw;
  
  .edit-item {
    margin-bottom: 24rpx;
    
    .label {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 8rpx;
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 24rpx;
    
    button {
      flex: 1;
      margin: 0 12rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .cancel-btn {
      background-color: #f5f5f5;
      color: #333;
    }
    
    .confirm-btn {
      background-color: #ffcc00;
      color: #333;
    }
  }
}

.purchase-notice {
  padding: 24rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  margin: 24rpx;
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 16rpx;
  }
  
  .content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.date-section {
  padding: 24rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  margin: 24rpx;
}

.uni-list-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .tit {
    font-size: 28rpx;
    color: #666;
  }
  
  .uni-list-cell-db {
    flex: 1;
    margin-left: 24rpx;
    
    .uni-input {
      font-size: 28rpx;
      color: #333;
      text-align: right;
    }
  }
}
</style> 